/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.util.op2parser.parsers.pyNastran;

import com.comac.ins.common.core.exception.base.BaseException;
import jep.SharedInterpreter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Map;

@Slf4j
public class OP2PythonExecutor {

    private static final String fileName = "read_op2.py";
    static String scriptPath;

    static {
        try {
            scriptPath = saveFile(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public synchronized static Map excute(String execFunction, String filePath){

        try(SharedInterpreter jep = new SharedInterpreter()){
            // 替换反斜杠为正斜杠
            filePath = filePath.replace("\\", "\\\\");

            log.info("python path:::"+scriptPath);
            String command = "result = " + execFunction + "(\"" + filePath + "\")";
            jep.runScript(scriptPath);
            jep.eval(command);

            Map resultMap = jep.getValue("result", Map.class);
            jep.close();
            if (resultMap == null) {
                return null;
            }
            // 如果 Python 返回了错误信息
            if (resultMap.containsKey("error")) {
                log.error("解析错误: {}", resultMap.get("error"));
                throw new BaseException("解析错误: " + resultMap.get("error"));
            }
            return resultMap;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BaseException(e.getMessage());
        }
    }

    public static String saveFile(String fileName) throws IOException {

        InputStream is = OP2PythonExecutor.class.getClassLoader().getResourceAsStream(fileName);
        String filePath = System.getProperty("user.dir");
        String path = filePath +File.separator+ fileName;
        File file = new File(path);
        FileUtils.copyInputStreamToFile(is, file);
        return path;
    }


    public static void main(String[] args) throws FileNotFoundException, ParseException {

    }
}
